//
//  ViewController.m
//  多线程练习
//
//  Created by dllo on 15/5/12.
//  Copyright (c) 2015年 lanou3g.com蓝鸥科技. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, retain) UIImageView *imageView;
@end

@implementation ViewController
- (void)dealloc
{
    [_imageView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(50, 100, 100, 30)];
    [button setTitle:@"点击" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [button release];
    NSLog(@"..");
    NSLog(@"hello");
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 200, 200, 200)];
    [self.imageView setBackgroundColor:[UIColor orangeColor]];
    [self.view addSubview:self.imageView];
    [self.imageView release];

}
- (void)buttonAction:(id)sender
{    //1
    //在主线程里创建子线程
//    [NSThread detachNewThreadSelector:@selector(runFor) toTarget:self withObject:nil];
//    NSLog(@"%s", __func__);
    //2
//    [self performSelectorInBackground:@selector(runFor) withObject:nil];
    
    //3
//    NSInvocationOperation *ope = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(runFor) object:nil];
//    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//    queue.maxConcurrentOperationCount = 1;
//    [queue addOperation:ope];
//    [ope release];
//    [queue release];
    
    //4
    NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
        [self runFor];
    }];
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [queue addOperation:block];
    [queue release];
    
}
- (void)runFor
{
    @autoreleasepool {
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://v.juhe.cn/movie/picurl?2583083"]];
        UIImage *image = [UIImage imageWithData:data];
        [self performSelectorOnMainThread:@selector(runInMain:) withObject:image waitUntilDone:YES];
    }
}

- (void)runInMain:(UIImage *)my
{
    [self.imageView setImage:my];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
